package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neuedu.his.po.User;
import com.neuedu.his.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/master/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 列出所有用户（逻辑未删除的）
     */
    @GetMapping("/list")
    public List<User> list() {
        var query = new LambdaQueryWrapper<User>()
                .eq(User::getDelMark, 1);
        return userService.list(query);
    }

    /**
     * 新增用户
     */
    @PostMapping("/save")
    public boolean saveUser(@RequestBody User user) {
        return userService.save(user);
    }

    /**
     * 更新用户
     */
    @PutMapping("/update")
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

    /**
     * 根据 ID 查用户
     */
    @GetMapping("/getById/{id}")
    public User getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    /**
     * 逻辑删除用户
     */
    @RequestMapping("/deleteById/{id}")
    public boolean deleteById(@PathVariable Integer id) {
        User u = new User();
        u.setId(id);
        u.setDelMark(0);
        return userService.updateById(u);
    }

    /**
     * 登录接口
     * 返回 token、userId、useType、username（用于前端显示）
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> creds) {
        String username = creds.get("username");
        String password = creds.get("password");

        User user = userService.getOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getUserName, username)
                        .eq(User::getPassword, password)
                        .eq(User::getDelMark, 1)
        );

        if (user == null) {
            return ResponseEntity
                    .status(401)
                    .body(Map.of("message", "用户名或密码错误"));
        }

        // 简单起见，用 userId 作为 token
        String token = "TOKEN_" + user.getId();

        Map<String, Object> resp = new HashMap<>();
        resp.put("token",    token);
        resp.put("userId",   user.getId());
        resp.put("useType",  user.getUseType());
        // 新增：将用户真实姓名/显示名返回给前端
        resp.put("username", user.getRealName());

        return ResponseEntity.ok(resp);
    }
}
